import {Router} from "express"
import { asyncHandler } from "../middleware/asyncHandler";
import { User } from "../../model/models/User";
import { MyFileDir } from "../../model/models/MyFileDirTable";
import { Favourite } from "../../model/models/Favourite";
import path from "path";
import { getIpAddress } from "@/utils/getIp";
import { PORT } from "@/utils/const";

const router = Router()


/**
 * @description: 得到用户的收藏
 * @param {number} id -1全部，  fileId表示相对应的文件id
 * @return {*}
 * @author: tao wenbo 2419421809@qq.com
 */
async function getFavourite(uid: number, id: number = -1, needAll: boolean = false) {
    let where: any = {};
    if (id !== -1) {
        where.fileId = id;
    }

    let result = await User.findByPk(uid, {
        attributes: {
            exclude: ["createdAt", "updatedAt", "deletedAt"],
        },
        include: [
            {
                model: MyFileDir,
                through: {
                    where,
                    paranoid: !needAll
                },
                as: "FavouriteMyFileDir",
            },
        ],
    });
    let arr = result?.dataValues.FavouriteMyFileDir || []
    return arr;
}

router.get(
    "",
    asyncHandler(async (req, res) => {
        let uid = (req as any).user.userId;
        let fileId = req.query.fileId || -1;
        let result = await getFavourite(uid, Number(fileId));
        for( let file of result ){
            file.dataValues.fileName = path.basename(file.dataValues.path)
            file.dataValues.thumbnailPath = "http://"+ getIpAddress()! + ":" + PORT +"/static"+ file.dataValues.thumbnailPath
        }
        return result
    })
);

router.post(
    "",
    asyncHandler(async (req, res) => {
        let fileId = req.body.fileId;
        let uid = (req as any).user.userId;
        let list = await getFavourite(uid, fileId)
        let isExit = list.length > 0;
        if (isExit) {
            throw new Error("已经喜欢过了");
        } else {
            let user = await User.findByPk(uid);
            let file = await MyFileDir.findByPk(fileId);
            if (!file?.dataValues.isFile) {
                throw new Error("只能喜欢视频哈！");
            } else {
                let id = 0
                try {
                    let result = await (user as any).addFavouriteMyFileDir(file);
                    id = result[0].dataValues.id
                } catch (error) {
                    // 表示存在已经删除的
                    let list = await getFavourite(uid, fileId, true)
                    id = list[0].dataValues.Favourite.dataValues.id
                    let favourite = await Favourite.findByPk(id, {
                        paranoid: false
                    })
                    await favourite?.restore()
                }
                return {
                    id
                }
            }
            
        }
    })
);



router.delete("/:id", asyncHandler( async (req, res) => {
    let id = (req.params as any).id
    let result = await Favourite.destroy({
        where: {
            id
        }
    })
    if( result === 0 ){
        throw new Error("取消失败")
    }else{
        return "取消成功"
    }
} ))


export default  router
